package com.zx.framework.web.interceptor.spring;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.zx.framework.core.env.CONST;
import com.zx.framework.core.exception.ExceptionCode;
import com.zx.framework.core.util.StringUtil;
import com.zx.framework.web.util.RequestUtil;
/**
 * session过滤器
 * @author stylewolf
 *
 */
public class SessionInterceptor extends HandlerInterceptorAdapter {
	
	private static final Logger LOGGER = Logger.getLogger(SessionInterceptor.class);
	
	/**
	 * session中保存的对象类型,如com.zx.framework.plat.user.vo.UserVo
	 */
	protected String sessionType;

	public String getSessionType() {
		return sessionType;
	}

	public void setSessionType(String sessionType) {
		this.sessionType = sessionType;
	}
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		request.setAttribute("basePath", request.getContextPath());
		//如果未指定session中的对象类型，此过滤器无效
		if(StringUtil.isEmpty(sessionType)){
			LOGGER.warn("sessionType属性未空，不启用session拦截器！");
			return super.preHandle(request, response, handler);
		}                                                                
		String url = RequestUtil.getRequestUri(request);
		LOGGER.debug("请求地址："+url+" iframe:"+request.getParameter("_iframe") +" _ajax:" +request.getParameter("_ajax") );
		Object sessionObject =request.getSession().getAttribute(CONST.SESSION_KEY);
		if(sessionObject==null){
//			if(RequestUtil.isAjax(request)){
//				response.setStatus(ExceptionCode.TIMEOUT);
//			}
//			else{
//				response.setStatus(ExceptionCode.AJAX_TIMEOUT);
//			}
			throw RequestUtil.throwTimeoutException(request, "系统登录超时！");
		}else{
			if(!sessionObject.getClass().getName().equals(sessionType)){
				throw RequestUtil.throwTimeoutException(request, "非法认证参数！");
			}
		}
		
		return super.preHandle(request, response, handler);
	}
}
